import Jenkins from 'jenkins';

export type BuildParametersType = {
  branchName: string;
};
export default class JenkinsApi {
  jenkins = null;
  name: string;
  branchKey: string;
  constructor(baseUrl, name?: string, branchKey?: string) {
    this.name = name;
    this.branchKey = branchKey || 'br';
    this.jenkins = new Jenkins({
      baseUrl: baseUrl,
    });
  }

  info(): Promise<boolean> {
    return this.jenkins.info();
  }

  exists(name?: string): Promise<boolean> {
    return this.jenkins.job.exists(name || this.name);
  }

  async getBranchList(name?: string) {
    const res = await this.jenkins.job.get(name || this.name);
    const allValueItems =
      res?.actions?.[0]?.parameterDefinitions?.[0]?.['allValueItems']?.values;
    return allValueItems || [];
  }

  async existsBranch(branchName: string, name?: string) {
    const list = await this.getBranchList(name || this.name);
    const exists = list.some((item) => {
      return item?.value.trim() === branchName.trim();
    });
    return [exists, list];
  }

  async build(
    parameters: BuildParametersType,
    name?: string,
  ): Promise<boolean> {
    const res = await this.jenkins.job.build({
      name: name || this.name,
      parameters: {
        [this.branchKey]: parameters?.branchName,
      },
    });
    return !!res;
  }

  getBuildLog(name: string, number: number) {
    const buildLog = this.jenkins.build.logStream(name, number);
    buildLog.on('data', (text) => {
      process.stdout.write(text);
    });
    buildLog.on('error', (err) => {
      console.log(err, null);
    });
    buildLog.on('end', () => {
      console.log(null, true);
    });
  }

  async buildTerm(name: string, number: number) {
    const res = await this.jenkins.build.term(name, number);
    return res;
  }

  async lastBuild(name: string) {
    const res = await this.jenkins.job.get(name);
    return res?.lastBuild?.number;
  }
}
